#ifndef DATAMANAGE_HPP
#define DATAMANAGE_HPP
#include <QCoreApplication>
#include <QFile>
#include <QTextStream>
#include <QMap>
#include <QStringList>
#include <QDebug>

class DataManager
{
public:
    DataManager(const QString& backup_file) : _backup_file(backup_file)
    {
        InitLoad();
    }

    bool Storage()
    {
        QFile file(_backup_file);
        if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
        {
            return false;
        }
        QTextStream out(&file);
        for (auto it = _table.begin(); it != _table.end(); ++it)
        {
            out << it.key() << " " << it.value() << "\n";
        }
        file.close();
        return true;
    }

    QStringList Split(const QString& str, const QString& sep)
    {
        return str.split(sep, Qt::SkipEmptyParts);
    }

    bool InitLoad()
    {
        QFile file(_backup_file);
        if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
        {
            return false;
        }
        QTextStream in(&file);
        QString body = in.readAll();
        file.close();

        QStringList lines = Split(body, "\n");
        for (const QString& line : lines)
        {
            QStringList parts = Split(line, " ");
            if (parts.size() == 2) {
                _table[parts[0]] = parts[1];
            }
        }
        return true;
    }

    bool Insert(const QString& filename, const QString& identifier)
    {
        _table[filename] = identifier;
        return Storage();
    }

    bool Updata(const QString& filename, const QString& identifier) {

        _table[filename] = identifier;
        return Storage();
    }

    bool GetOneByFileName(const QString& filename, QString* identifier)
    {
        if (_table.contains(filename))
        {
            *identifier = _table[filename];
            return true;
        }
        return false;
    }

private:
    QString _backup_file;
    QMap<QString, QString> _table;
};

#endif // DATAMANAGE_HPP
